<template>
	<div class="login-container">
		<!-- 游戏标题 -->
		<div class="game-title">
			<h1 class="title-main">五绝传说</h1>
			<p class="title-sub">挂机江湖</p>
		</div>
		
		<!-- 登录表单 -->
		<div class="login-form">
			<!-- 登录方式切换 -->
			<div class="login-tabs">
				<div 
					class="tab-item" 
					:class="{active: loginMode === 'guest'}"
					@click="switchLoginMode('guest')"
				>
					游客登录
				</div>
				<div 
					class="tab-item" 
					:class="{active: loginMode === 'phone'}"
					@click="switchLoginMode('phone')"
				>
					手机登录
				</div>
			</div>
			
			<!-- 游客登录 -->
			<div v-if="loginMode === 'guest'" class="guest-login">
				<div class="form-item">
					<label class="form-label">设备ID</label>
					<input 
						id="deviceId"
						name="deviceId"
						class="form-input" 
						v-model="guestForm.deviceId" 
						placeholder="自动生成设备ID"
						disabled
					/>
				</div>
				<button class="login-btn" @click="guestLogin" :disabled="loginLoading">
					{{ loginLoading ? '登录中...' : '游客登录' }}
				</button>
			</div>
			
			<!-- 手机登录 -->
			<div v-if="loginMode === 'phone'" class="phone-login">
				<div class="form-item">
					<label class="form-label">手机号</label>
					<input 
						id="phone"
						name="phone"
						class="form-input" 
						v-model="phoneForm.phone" 
						placeholder="请输入手机号"
						maxlength="11"
						type="tel"
					/>
				</div>
				<div class="form-item">
					<label class="form-label">验证码</label>
					<div class="code-input-wrapper">
						<input 
							id="verificationCode"
							name="verificationCode"
							class="form-input code-input" 
							v-model="phoneForm.code" 
							placeholder="请输入验证码"
							maxlength="6"
							type="number"
						/>
						<button 
							class="code-btn" 
							@click="sendCode" 
							:disabled="codeLoading || countdown > 0"
						>
							{{ countdown > 0 ? `${countdown}s` : (codeLoading ? '发送中...' : '获取验证码') }}
						</button>
					</div>
				</div>
				<button class="login-btn" @click="phoneLogin" :disabled="loginLoading">
					{{ loginLoading ? '登录中...' : '手机登录' }}
				</button>
			</div>
		</div>
		
		<!-- 协议条款 -->
		<div class="agreement">
			<div class="agreement-item">
				<label class="checkbox-label">
					<input 
						id="agreementCheckbox"
						name="agreementCheckbox"
						type="checkbox" 
						v-model="agreed" 
					/>
					<span class="agreement-text">我已阅读并同意</span>
					<span class="agreement-link" @click="showAgreement('user')">《用户协议》</span>
					<span class="agreement-text">和</span>
					<span class="agreement-link" @click="showAgreement('privacy')">《隐私政策》</span>
				</label>
			</div>
		</div>
	</div>
</template>

<script>
import request from '../../src/api/request.js'

export default {
	name: 'LoginPage',
	data() {
		return {
			// 登录模式
			loginMode: 'guest',
			
			// 游客登录表单
			guestForm: {
				deviceId: this.generateDeviceId()
			},
			
			// 手机登录表单
			phoneForm: {
				phone: '',
				code: ''
			},
			
			// 加载状态
			loginLoading: false,
			codeLoading: false,
			countdown: 0,
			
			// 协议同意状态
			agreed: false,
			
			// 自动登录状态
			autoLoginLoading: false
		}
	},
	
	mounted() {
		// 检查是否为登录页面
		if (this.isLoginPage()) {
			this.checkAutoLogin()
		}
	},
	
	methods: {
		/**
		 * 检查当前页面是否为登录页面
		 */
		isLoginPage() {
			const currentHash = window.location.hash
			return currentHash.includes('/pages/login/index') || currentHash === '#/' || currentHash === ''
		},
		
		/**
		 * 检查自动登录
		 */
		async checkAutoLogin() {
			const yid = localStorage.getItem('yid')
			if (yid) {
				await this.loadRoleInfo()
			}
		},
		
		/**
		 * 加载角色信息（自动登录）
		 */
		async loadRoleInfo() {
			this.autoLoginLoading = true
			
			try {
			// 获取本地存储的yid
			const yid = localStorage.getItem('yid')
			const userId = localStorage.getItem('userId')
			
			if (!yid || !userId) {
				return
			}
			
			// 调用自动登录接口
			const response = await request.post('/user/login', {
				mode: 'auto_login',
				yid: yid
			})
				
				if (response && response.code) {

					if (response.code === 1) {
					// 自动登录成功，跳转到角色选择页面
					(typeof uni !== 'undefined' ? uni.setStorageSync('role_list', JSON.stringify(response.data.role_list || [])) : localStorage.setItem('role_list', JSON.stringify(response.data.role_list || [])))
					window.location.hash = '/pages/role-select/index'
					return
					} else if (response.code < 0) {
					// 自动登录失败，清除yid并停留在登录页
					if (typeof uni !== 'undefined') {
					uni.removeStorageSync('yid')
					uni.removeStorageSync('role_id')
					} else {
					localStorage.removeItem('yid')
					localStorage.removeItem('role_id')
					}
					}
				}
			} catch (error) {
				console.error('自动登录请求失败:', error)
				// 请求失败时清除本地存储
				if (typeof uni !== 'undefined') {
				uni.removeStorageSync('yid')
				uni.removeStorageSync('role_id')
				} else {
				localStorage.removeItem('yid')
				localStorage.removeItem('role_id')
				}
			} finally {
				this.autoLoginLoading = false
			}
		},
		
		/**
		 * 切换登录模式
		 */
		switchLoginMode(mode) {
			this.loginMode = mode
		},
		
		/**
		 * 生成设备ID
		 */
		generateDeviceId() {
			return 'device_' + Date.now() + '_' + Math.random().toString(36).substr(2, 9)
		},
		
		/**
		 * 游客登录
		 */
		async guestLogin() {
			if (!this.agreed) {
				alert('请先同意用户协议和隐私政策')
				return
			}
			
			this.loginLoading = true
			
			try {
				// 使用新的API调用方式
				const api = await import('@/api')
				const result = await api.authApi.guestLogin(this.guestForm.deviceId)
				// 游客登录成功，跳转到角色选择页面
				localStorage.setItem('yid', result.data.yid)
				localStorage.setItem('userId', result.data.user_id)
				localStorage.setItem('role_list', JSON.stringify(result.data.role_list || []))
				window.location.hash = '/pages/role-select/index'
			} catch (error) {
				console.error('游客登录失败:', error)
				alert(error.message || '登录失败，请重试')
			} finally {
				this.loginLoading = false
			}
		},
		
		/**
		 * 发送验证码
		 */
		async sendCode() {
			if (!this.phoneForm.phone) {
				alert('请输入手机号')
				return
			}
			
			if (!/^1[3-9]\d{9}$/.test(this.phoneForm.phone)) {
				alert('请输入正确的手机号')
				return
			}
			
			this.codeLoading = true
			
			try {
				// 使用新的API调用方式
				const api = await import('@/api')
				await api.authApi.sendVerifyCode(this.phoneForm.phone)
				
				// 开始倒计时
				this.countdown = 60
				const timer = setInterval(() => {
					this.countdown--
					if (this.countdown <= 0) {
						clearInterval(timer)
					}
				}, 1000)
				
				alert('验证码已发送')
				
			} catch (error) {
				console.error('发送验证码失败:', error)
				alert(error.message || '发送失败，请重试')
			} finally {
				this.codeLoading = false
			}
		},
		
		/**
		 * 手机登录
		 */
		async phoneLogin() {
			if (!this.agreed) {
				alert('请先同意用户协议和隐私政策')
				return
			}
			
			if (!this.phoneForm.phone || !this.phoneForm.code) {
				alert('请输入手机号和验证码')
				return
			}
			
			this.loginLoading = true
			
			try {
				// 使用新的API调用方式
				const api = await import('@/api')
				const result = await api.authApi.phoneLogin(this.phoneForm.phone, this.phoneForm.code)
				
				// 登录成功，保存yid和用户信息
				localStorage.setItem('yid', result.data.yid)
				localStorage.setItem('userId', result.data.user_id)
				localStorage.setItem('roleList', JSON.stringify(result.data.role_list || []))
				
				// 跳转到角色选择页面
				window.location.hash = '/pages/role-select/index'
			} catch (error) {
				console.error('手机登录失败:', error)
				alert(error.message || '登录失败，请重试')
			} finally {
				this.loginLoading = false
			}
		},
		
		/**
		 * 显示协议
		 */
		showAgreement(type) {
			if (type === 'user') {
				alert('用户协议内容')
			} else if (type === 'privacy') {
				alert('隐私政策内容')
			}
		}
	}
}
</script>

<style scoped>
.login-container {
	min-height: 100vh;
	background: linear-gradient(135deg, #1e3c72 0%, #2a5298 100%);
	display: flex;
	flex-direction: column;
	align-items: center;
	justify-content: center;
	padding: 20px;
	box-sizing: border-box;
}

.game-title {
	text-align: center;
	margin-bottom: 40px;
}

.title-main {
	font-size: 36px;
	font-weight: bold;
	color: #ffffff;
	margin: 0 0 10px 0;
	text-shadow: 2px 2px 4px rgba(0,0,0,0.5);
}

.title-sub {
	font-size: 16px;
	color: #b8d4f0;
	margin: 0;
}

.login-form {
	background: rgba(255, 255, 255, 0.95);
	border-radius: 12px;
	padding: 30px;
	width: 100%;
	max-width: 400px;
	box-shadow: 0 8px 32px rgba(0,0,0,0.3);
}

.login-tabs {
	display: flex;
	margin-bottom: 30px;
	border-radius: 8px;
	overflow: hidden;
	border: 1px solid #e0e0e0;
}

.tab-item {
	flex: 1;
	padding: 12px;
	text-align: center;
	background: #f5f5f5;
	cursor: pointer;
	transition: all 0.3s ease;
	color: #666;
}

.tab-item.active {
	background: #007AFF;
	color: white;
}

.form-item {
	margin-bottom: 20px;
}

.form-label {
	display: block;
	margin-bottom: 8px;
	color: #333;
	font-weight: 500;
}

.form-input {
	width: 100%;
	padding: 12px;
	border: 1px solid #ddd;
	border-radius: 6px;
	font-size: 16px;
	box-sizing: border-box;
	transition: border-color 0.3s ease;
}

.form-input:focus {
	outline: none;
	border-color: #007AFF;
}

.form-input:disabled {
	background: #f5f5f5;
	color: #999;
}

.code-input-wrapper {
	display: flex;
	gap: 10px;
}

.code-input {
	flex: 1;
}

.code-btn {
	padding: 12px 16px;
	background: #007AFF;
	color: white;
	border: none;
	border-radius: 6px;
	cursor: pointer;
	white-space: nowrap;
	transition: background 0.3s ease;
}

.code-btn:hover:not(:disabled) {
	background: #0056CC;
}

.code-btn:disabled {
	background: #ccc;
	cursor: not-allowed;
}

.login-btn {
	width: 100%;
	padding: 14px;
	background: #007AFF;
	color: white;
	border: none;
	border-radius: 6px;
	font-size: 16px;
	font-weight: 500;
	cursor: pointer;
	transition: background 0.3s ease;
	margin-top: 10px;
}

.login-btn:hover:not(:disabled) {
	background: #0056CC;
}

.login-btn:disabled {
	background: #ccc;
	cursor: not-allowed;
}

.agreement {
	margin-top: 20px;
	text-align: center;
}

.checkbox-label {
	display: flex;
	align-items: center;
	justify-content: center;
	gap: 5px;
	font-size: 14px;
	color: #ffffff;
	cursor: pointer;
}

.agreement-text {
	color: #b8d4f0;
}

.agreement-link {
	color: #ffffff;
	text-decoration: underline;
	cursor: pointer;
}

.agreement-link:hover {
	color: #e0e0e0;
}
</style>